<template>
  <div class="app-container">

    <el-container>
      <el-header style="height: auto;">
        <el-row :gutter="2" type="flex">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-row>
              <el-col :xs="24" :sm="24" :md="12" :lg="5" :xl="5">
                <el-select v-model="web_id" v-loading="websLoading" style="width: 70%" size="mini" placeholder="输出站点" clearable filterable @change="handleSearchWPAccount">
                  <el-option
                    v-for="web in webs"
                    :key="web.id"
                    :label="web.url"
                    :value="web.id"
                  />
                </el-select>
                <el-button
                  style="width: 20%"
                  size="mini"
                  type="warning"
                  title="管理"
                  icon="el-icon-setting"
                  @click="webVisible = true"
                />
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="2" :xl="2">
                <el-button
                  type="success"
                  size="mini"
                  title="添加"
                  icon="el-icon-plus"
                  @click="showAddNewTopic"
                >添加
                </el-button>
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="7" :xl="7">
                <el-row :gutter="20">
                  <!--              <el-col :span="4">-->
                  <!--                <el-button size="mini"  icon="el-icon-s-grid" @click="drawer=true"></el-button>-->
                  <!--              </el-col>-->
                  <el-col :span="4">
                    <el-popover
                      v-model="more_filter"
                      placement="top"
                      width="400"
                    >
                      <el-row>
                        <el-col :span="12">
                          <el-input v-model="keyword" placeholder="请输入内容" size="mini" clearable>
                            <template slot="prepend">关键词</template>
                          </el-input>
                        </el-col>
                        <el-col :span="12">
                          <el-input v-model="TagInput" placeholder="请输入内容" clearable size="mini">
                            <template slot="prepend">TAG</template>
                          </el-input>
                        </el-col>
                      </el-row>
                      <el-row>
                        <el-col :span="12">
                          <el-input v-model.number="volume" type="number" placeholder="min volume" size="mini" clearable @input="validateSearchVolume">
                            <template slot="prepend">VOL</template>
                          </el-input>
                        </el-col>
                        <el-col :span="12">
                          <el-input v-model.number="difficulty" type="number" placeholder="max difficulty" clearable size="mini" @input="validateSearchDifficulty">
                            <template slot="prepend">DFF</template>
                          </el-input>
                        </el-col>
                      </el-row>
                      <el-icon v-if="keyword !== ''" slot="reference" style="color: red" class="el-icon-medal-1">更多</el-icon>
                      <el-icon v-else slot="reference" class="el-icon-medal">更多</el-icon>
                    </el-popover>
                    <i class="el-icon-delete" title="清空其他选项" @click="handleClean()" />
                  </el-col>
                  <el-col :span="16">
                    <el-input
                      v-model="kwInput"
                      size="mini"
                      placeholder="输入关键词进行筛选"
                      class="input-with-select"
                      clearable
                      @keyup.native.enter="handleSearch"
                    >
                      <el-button slot="append" size="mini" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                    </el-input>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="5" :xl="5">
                <el-slider
                  v-model="progress"
                  style="display: inline-block; width: 90%"
                  range
                  :format-tooltip="progressToolTips"
                  show-input
                  :max="100"
                  @change="handleSearch"
                />

                <!--              <span style="margin-left: 3px;vertical-align: center;">{{progress[1]}}</span>-->
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="5" :xl="5">
                <el-slider
                  v-model="stars"
                  style="display: inline-block; width: 90%"
                  range
                  :format-tooltip="starToolTips"
                  show-input
                  :min="1"
                  :max="5"
                />
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-alert
          v-if="accountAlertTitle.length"
          :title="accountAlertTitle"
          style="height: 30px"
          type="error"
        />
      </el-header>
      <el-container>
        <el-main>
          <el-row>
            <el-col :span="12">
              <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item><a type="text" @click="handleToTopNode()">顶层</a></el-breadcrumb-item>
                <el-breadcrumb-item v-if="current_expended_node && current_expended_node.parent_id"><a type="text" @click="handleIDSearch(current_expended_node.parent_id)">{{ current_expended_node.parent_id }}</a></el-breadcrumb-item>
                <el-breadcrumb-item v-if="current_expended_node"><span style="color: red !important;">{{ current_expended_node.id }}|{{ current_expended_node.keyword }}</span></el-breadcrumb-item>
                <span
                  v-if="current_expended_node&&current_expended_node.id"
                  style="
                padding: 4px 10px;
                background-color: #67c23a;
                color: white;
                border-radius: 4px;
                cursor: pointer;
                display: inline-block;
                font-size: 12px;
                transition: all 0.3s;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
              "
                  onmouseover="this.style.backgroundColor='#66b1ff'"
                  onmouseout="this.style.backgroundColor='#409EFF'"
                  @click.stop="() => append(current_expended_node)"
                >添加子</span>
                <span
                  style="
                padding: 4px 10px;
                color: dodgerblue;
                border-radius: 4px;
                cursor: pointer;
                display: inline-block;
                font-size: 12px;
                transition: all 0.3s;
              "
                  @click.stop="() => copyChildrenTitles(current_expended_node.id)"
                ><el-icon title="复制下所有子标题" class="el-icon-copy-document" /></span>
              </el-breadcrumb>
            </el-col>
            <el-col :span="12">
              <el-input
                v-model="filterText"
                size="mini"
                placeholder="输入关键字进行过滤"
              />
            </el-col>
          </el-row>

          <el-tree
            ref="TopicTree"
            v-loading="listLoading"
            :data="data"
            :accordion="true"
            :load="loadNode"
            lazy
            :expand-on-click-node="false"
            node-key="id"
            highlight-current
            :default-expanded-keys="expanded_ids"
            :indent="20"
            :filter-node-method="filterNode"
            :props="{ children: 'children', label: 'title' }"
            @node-drop="handleNodeDrop"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <div class="node-title" @click="handleSearchNodeByParentID(data)">
                <el-tooltip :content="data.keyword" placement="top" :disabled="!isOverflowing(data.keyword)">
                  <span :class="{'keyword-text': true, 'deleted': data.deleted}" :style="{ color: data.title && data.title !== data.keyword ? 'green' : 'black' }">
                    {{ data.parent_id&&data.title.length > 0 ? data.title : data.keyword }}
                  </span>
                </el-tooltip>
                <span v-if="data.children_count" class="children-count">{{ data.children_count }}</span>
              </div>
              <div class="node-info-actions">
                <div class="node-actions">
                  <el-popover
                    placement="top-start"
                    title="详情"
                    width="600"
                    trigger="click"
                  >
                    <div class="custom-row">
                      <span class="row-title">ID:</span>
                      <span class="row-content">{{ data.id }}</span>
                    </div>
                    <div class="custom-row">
                      <span class="row-title">关键词:</span>
                      <span class="row-content">{{ data.keyword }}</span>
                    </div>
                    <div class="custom-row">
                      <span class="row-title">标题:</span>
                      <span class="row-content">{{ data.title }}</span>
                    </div>
                    <div class="custom-row">
                      <el-input v-model="data.description" style="max-height: 400px" type="textarea" rows="10" disabled />
                    </div>
                    <i slot="reference" class="el-icon-info mt-icon" />
                  </el-popover>
                  <el-tag v-if="data.status === 'pending'" type="warning">审核中</el-tag>
                  <el-tag v-else-if="data.status === 'approved'" type="success">审核通过</el-tag>
                  <el-button v-else type="danger" size="mini" icon="el-icon-s-check" @click.stop="handleSaveQuickEditTopic(data, 'status', 'pending')">提交审核</el-button>
                  <el-button type="success" size="mini" icon="el-icon-plus" @click.stop="() => append(data)">子框架</el-button>
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click.stop="handleDirectlyEditTopic(data)">编辑</el-button>
                  <el-tooltip content="复制链接" placement="top">
                    <i class="el-icon-copy-document" @click.stop="handleCopyLink(data)" />
                  </el-tooltip>
                  <el-tooltip :content="data.post_url ? '打开博客' : '未发布(google搜索)'" placement="top">
                    <i :class="['el-icon-link', {'is-active': data.post_url}]" @click.stop="handleOpenPost(data)" />
                  </el-tooltip>

                  <el-tooltip :content="data.total_post ? `总共${data.total_post}` : '添加post'" placement="top">
                    <i :class="['el-icon-document-add', {'is-active': data.total_post}]" @click.stop="handleAddPost(data)" />
                  </el-tooltip>
                  <el-tooltip v-if="data.serp_finished" content="查看SERP" placement="top">
                    <i class="el-icon-folder-add" />
                  </el-tooltip>
                  <el-tooltip :content="data.deleted ? '已删除' : '删除框架'" placement="top">
                    <i :class="['el-icon-delete', {'is-active': !data.deleted}]" @click.stop="handleClickDelete(data)" />
                  </el-tooltip>
                </div>
                <div class="node-info">
                  <el-tag v-if="data.status === 'pending'" type="warning">审核中</el-tag>
                  <el-tag v-else-if="data.status === 'approved'" type="success">通过</el-tag>
                  <el-tag v-else-if="data.status === 'rejected'" type="danger">已驳回</el-tag>
                  <span v-if="data.crawl_count && data.crawl_count > 0">
                    <el-tag :type=" data.crawl_count > 10 ? 'success': 'warning'">{{ getAiStatusTag(data.crawl_count) }}</el-tag>
                  </span>
                  <span v-if="data.progress > 10">
                    <el-tag>{{ data.progress }}%</el-tag>
                  </span>
                  <span class="volume-tag">
                    <el-tag :type="getVolumeTagType(data.volume)">{{ data.volume }}</el-tag>
                  </span>
                  <span class="difficulty-tag">
                    <el-tag :type="getDifficultyTagType(data.difficulty)" :title="'难度:' + data.difficulty + '搜索量:' + data.volume">{{ data.difficulty }}</el-tag>
                  </span>
                  <el-rate v-model="data.star" @change="handleSaveTopic(data)" />
                </div>

              </div>
            </span>
          </el-tree>

          <el-button v-if="web_id !== ''" type="success" size="mini" style="margin-top: 10px;float: left;display: inline-block" @click="handleGetWPPostStatics">发帖比例统计</el-button>
          <AITask
            task-name="content_richness_analysis"
            :params="{
              web_id: web_id,
            }"
            button-text="AI分析话题矩阵布局"
            button-type="primary"
            button-icon="el-icon-s-opportunity"
            dialog-title="AI分析话题矩阵布局"
            show_name="AI分析话题矩阵布局"
          />
          <el-button v-if="id !== ''" type="primary" size="mini" style="margin-top: 10px;float: left;display: inline-block" @click="showMutliEdit">批量设置</el-button>
          <el-pagination
            v-if="data.length"
            background
            class="mt-pagination"
            :current-page="page"
            :page-sizes="[10, 20,100,200,1000]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </el-main>
      </el-container>
    </el-container>
    <el-dialog
      v-loading.fullscreen.lock="deleteDialogLoading"
      :title="deleteDialogTitle"
      :visible.sync="deleteDialogVisible"
      style="margin-top: 148px !important;"
    >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleDeleteConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-drawer
      v-loading="topicpromptgenerateloading"
      :title="titleTopicDialog"
      :wrapper-closable="false"
      :visible.sync="titleTopicDialogVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="true"
      :size="drawer_size"
      @open="handleShowMaterial()"
    >
      <div v-if="topic_id" style="margin-left: 10px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="showMaterial ? 16 : 24" :xl="showMaterial ? 16 : 24" style="border-right: 3px solid black;">
            <el-tabs v-model="activeOptionsName">
              <el-tab-pane label="核心" name="first">
                <el-form ref="dataForm" :model="topicTemp" label-position="left" label-width="100px">
                  <el-form-item label="关键词">
                    <el-input v-model="topicTemp.keyword" placeholder="核心关键词" style="max-width: 400px;" size="mini" />
                    <el-input v-if="topicTemp.keyword && topicTemp.keyword.split('\n').length > 1" v-model="topicTemp.title_template" style="max-width: 300px" size="mini" placeholder="template" />
                    搜索量<el-input v-model.number="topicTemp.volume" type="number" size="mini" style="width: 100px" placeholder="数字" @input="validateVolume" />
                    难度<el-input v-model.number="topicTemp.difficulty" type="number" size="mini" style="width: 100px" placeholder="0-100" @input="validateDifficulty" />
                    优先级:<el-rate
                      v-model="topicTemp.star"
                      style="display: inline-block"
                      :texts="['目录属性', '收集草稿', '等待分析', '准备推广', '马上推广']"
                      show-text
                    />
                  </el-form-item>
                  <el-form-item label="文章标题">
                    <el-row>
                      <el-col :span="18">
                        <el-input v-model="topicTemp.title" size="mini" style="width: 100%" />
                        <el-alert v-if="topicTemp.keyword.split('\n').length > 1 && topicTemp.title !== ''" type="warning" title="批量添加;不需要填标题，内容如果不为空，则会导致所有话题内容一样！！" />
                      </el-col>
                      <el-col :span="6">
                        <el-button
                          v-if="topicTemp.id && topicTemp.status !== 'approved'"
                          size="mini"
                          icon="el-icon-data-analysis"
                          style="background-color: #1EB7E6; border-color: #1EB7E6; color: white; margin-right: 5px;"
                          @click="handleShowTopicAnalysis"
                        >
                          AI数据分析
                        </el-button>
                        <el-tag v-if="topicTemp.status === 'pending'" type="warning">审核中</el-tag>
                        <el-tag v-else-if="topicTemp.status === 'approved'" type="success">审核通过</el-tag>
                        <el-button v-else type="danger" size="mini" icon="el-icon-s-check" @click.stop="handleSaveQuickEditTopic(topicTemp, 'status', 'pending')">提交审核</el-button>
                        <AITask
                          task-name="aititleanalysis"
                          :params="{
                            title: topicTemp.title,
                            keyword: topicTemp.keyword
                          }"
                          button-text="AI分析"
                          button-type="primary"
                          button-icon="el-icon-s-opportunity"
                          dialog-title="AI标题分析"
                          show_name="AI标题分析"
                        />
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="文章框架">
                    <aicontent :replace_data="{keyword: topicTemp.keyword, title: topicTemp.title}" color="#1890ff" app="content" class="editor-upload-btn" @successCBK="openAiSuccessCBK" />
                    <el-popover
                      placement="top-start"
                      title="prompts模板提示"
                      width="200"
                      trigger="click"
                      content="关键词:keyword, title"
                    >
                      <span slot="reference"><i class="el-icon-info" /></span>
                    </el-popover>

                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-setting"
                      title="prompt shortcode"
                      @click="aipromptVisible = true"
                    />
                    <div style="margin-top: 20px;margin-left: 40px; display: inline-block">
                      <el-button-group>
                        <el-button size="mini" type="primary" icon="el-icon-notebook-2" @click="handleAutoGetArticlePrompt('框架')">调研框架</el-button>
                        <el-button size="mini" type="primary" @click="handleAutoGetArticlePrompt('数据')">调研数据<i class="el-icon-data-line el-icon--right" /></el-button>
                      </el-button-group>
                    </div>
                    <AITask
                      task-name="task_topic_section_analysis"
                      :params="{
                        topic_id: topicTemp.id,
                        title: topicTemp.title,
                        keyword: topicTemp.keyword,
                        description: topicTemp.description
                      }"
                      button-text="AI调研框架"
                      button-type="success"
                      button-icon="el-icon-cpu"
                      dialog-title="AI调研框架"
                      show_name="AI调研框架"
                      @final-result="handleAITopicSectionAnalysisResult"
                    />

                    <el-alert v-if="generateresponse !== ''" type="warning">
                      {{ generateresponse }}
                    </el-alert>
                    <el-alert v-else type="warning">
                      {{ aiStatusMessage }}
                    </el-alert>
                    <!--          <tinymce ref="mt" :height="300" v-model="topicTemp.description"></tinymce>-->
                    <!--          <simplemde-md :id="md_id" :value="topicTemp.description" placeholder="markdown标记" style="display: block"></simplemde-md>-->
                    <!--                 <el-input style="max-height: 400px" type="textarea" rows="10" v-model="topicTemp.description" placeholder="# 一级标题 ## 二级标题 注意#号于内容质检有个空格"></el-input>-->
                    <v-md-editor
                      v-model="topicTemp.description"
                      height="400px"
                      :disabled-menus="['image',
                                        'code',
                                        'bold',
                                        'italic',
                                        'strike',
                                        'line',
                                        'quote',
                                        'list',
                                        'ordered-list',
                                        'check',
                                        'install',
                                        'link']"
                      placeholder="# 一级标题 ## 二级标题 注意#号于内容之间有个空格"
                      @change="handleEditorChange"
                    />
                    <el-alert v-if="topicTemp.description.indexOf('# 一级标题') !== -1" type="warning" title="!初始内容未删除,模板不会处理" />
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="其他参数" name="second">
                <el-form ref="dataForm" :model="topicTemp" label-position="left" label-width="100px">
                  <el-form-item label="ID">
                    <el-input v-model="topicViewData.id" size="mini" disabled type="number" style="display: inline-block; max-width: 100px" />
                    父级ID:<el-input v-model="topicTemp.parent_id" size="mini" placeholder="输入父级框架ID" style="display: inline-block; max-width: 100px" />
                    <el-alert v-if="topicTemp.title.split('\n').length > 1 && topicTemp.parent_id === ''" type="warning" title="父级元素为空，编辑状态批量添加无效" />

                    <!--           <el-button @click="openaiDialogVisible=true" type="primary" size="mini">AI Writer</el-button>-->
                  </el-form-item>
                  <el-form-item label="框架类型:">
                    <el-row>
                      <el-col :span="8">类型用途:
                        <el-select v-model="topicTemp.category_id" placeholder="类型用途" size="mini" class="head" clearable>
                          <el-option
                            v-for="category in categories"
                            :key="category.id"
                            :label="category.name"
                            :value="category.id"
                          />
                        </el-select>
                      </el-col>
                      <el-col :span="8">
                        功能类型:
                        <el-select v-model="topicTemp.strategy_id" placeholder="功能类型" size="mini" class="head" clearable>
                          <el-option
                            v-for="strategy in strategies"
                            :key="strategy.id"
                            :label="strategy.name"
                            :value="strategy.id"
                          />
                        </el-select>
                      </el-col>
                      <el-col :span="8">
                        AI:
                        <el-select v-model="topicTemp.ai_writer" placeholder="AI类型" size="mini" class="head" clearable>
                          <el-option
                            v-for="item in ai_writers"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="其他参数">
                    <el-row>
                      <!--            <span>推广/tag:<el-input size='mini' v-model="topicTemp.tag" style="width: 200px"></el-input></span>-->
                      输出博客:
                      <el-select v-model="topicTemp.web_id" v-loading="websLoading" size="mini" placeholder="输出站点" clearable filterable style="width: 300px;">
                        <el-option
                          v-for="web in webs"
                          :key="web.id"
                          :label="web.url"
                          :value="web.id"
                        />
                      </el-select>
                      写手:
                      <el-select v-model="topicTemp.writer_id" size="mini" placeholder="指定写手" filterable clearable style="width: 150px;">
                        <el-option label="不指定" value="" />
                        <el-option
                          v-for="user in users"
                          :key="user.id"
                          :label="user.show_name"
                          :value="user.id"
                        />
                      </el-select>
                    </el-row>
                    <el-row style="margin-top: 10px" :gutter="40">
                      <!--            <el-col :span="6">-->
                      <!--               爬取素材:<el-switch-->
                      <!--                    v-model="topicTemp.serp_crawl"-->
                      <!--                    active-color="#13ce66"-->
                      <!--                    inactive-color="#ff4949">-->
                      <!--                  </el-switch>-->
                      <!--              <span style="margin-left: 10px">完成:</span><el-switch-->
                      <!--                    v-model="topicTemp.serp_finished"-->
                      <!--                    active-color="#13ce66"-->
                      <!--                    inactive-color="#ff4949">-->
                      <!--                  </el-switch>-->
                      <!--            </el-col>-->
                      <el-col :span="12">
                        <div>
                          <span>进度:</span>
                          <el-input slot="reference" v-model.number="topicTemp.progress" style="width: 150px; display: inline-block; margin-left: 10px" size="mini" type="number" placeholder="0-100" @input="validateProgress" />
                          <el-popover
                            placement="top-start"
                            title="提示"
                            width="400"
                            trigger="hover"
                          >
                            <el-alert
                              title="进度小于5"
                              type="success"
                              description="自动化AI必须小于5才会进行自动编辑，大于5的内容不会进入自动化"
                            />
                            <el-alert
                              title="91-99"
                              type="warning"
                              description="作为自定义优先级配合使用"
                            />
                            <el-icon slot="reference" size="mini" class="el-icon-info" />
                          </el-popover>
                          <!--               <el-slider-->
                          <!--                 style="width: 200px;display: inline-block; margin: auto;"-->
                          <!--                v-model="topicTemp.progress"-->
                          <!--                 @change="handleSearch"-->
                          <!--                :max="100">-->
                          <!--              </el-slider>-->
                        </div>
                      </el-col>
                      <el-col :span="6">
                        <el-button type="text" @click="handleClickPublish">自动发布设置</el-button>
                        <el-tag v-if="topicTemp.auto_post_account_id">wp账号:{{ topicTemp.auto_post_account_id }} | {{ post_domain }} </el-tag>
                        <el-tag v-if="topicTemp.auto_post_category">目录id:{{ topicTemp.auto_post_category }} </el-tag>
                        <el-tag v-if="topicTemp.auto_post_tags">tag:{{ topicTemp.auto_post_tags }} </el-tag>
                      </el-col>

                    </el-row>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
            <el-row :gutter="20" style="margin-left: auto;margin-right: 0; text-align: center;">
              <el-tag v-if="topicViewData.ai_prompte_finished">AI正在生成内容...</el-tag>
              <el-button v-else type="primary" style="display: inline-block" title="点击开始写文章" @click="handleRewrite('aiwrite')">写文章</el-button>
              <el-button style="display: inline-block" @click="handleCleanTopicForm">清空内容</el-button>
              <el-button style="display: inline-block" @click="titleTopicDialogVisible = false">取 消</el-button>
              <!--              <el-button style="display: inline-block" type="danger" @click="handleAddTopic" :loading="saveTopicLoading">保 存</el-button>-->
              <el-dropdown :loading="saveTopicLoading" split-button type="success" @click="handleCheckAddTopic()">
                保 存
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native.stop="handleCheckAddTopic('aiwrite')">保存并开始写内容</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </el-col>
          <el-col v-if="showMaterial && topic_id" :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
            <topicmaterial :topic_id="topic_id" :topic_title="topic_title" :web-visible="materialVisible" />
          </el-col>
        </el-row>
      </div>
      <div v-else style="margin-left: 10px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="showMaterial ? 16 : 24" :xl="showMaterial ? 16 : 24" style="border-right: 3px solid black;">
            <el-form ref="dataForm" :model="topicTemp" label-position="left" label-width="100px">
              <el-form-item label="父级ID">
                <el-input v-model="topicTemp.parent_id" size="mini" placeholder="输入父级框架ID" style="display: inline-block; max-width: 100px" />
                <el-alert v-if="topicTemp.keyword.split('\n').length > 1 && topicTemp.parent_id === ''" type="warning" title="父级元素为空，编辑状态批量添加无效" />
                优先级:<el-rate
                  v-model="topicTemp.star"
                  style="display: inline-block"
                  :texts="['目录属性', '收集草稿', '等待分析', '准备推广', '马上推广']"
                  show-text
                />
                <!--           <el-button @click="openaiDialogVisible=true" type="primary" size="mini">AI Writer</el-button>-->
                <aicontent :replace_data="{keyword: topicTemp.keyword, title: topicTemp.title}" color="#1890ff" app="content" class="editor-upload-btn" @successCBK="openAiSuccessCBK" />
                <el-popover
                  placement="top-start"
                  title="prompts模板提示"
                  width="200"
                  trigger="click"
                  content="此处支持关键词:keyword, title"
                >
                  <span slot="reference"><i class="el-icon-info" /></span>
                </el-popover>
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-setting"
                  title="prompt shortcode"
                  @click="aipromptVisible = true"
                />
                <div style="margin-top: 20px;margin-left: 40px; display: inline-block">
                  <el-radio-group v-model="generate_type" size="mini">
                    <el-radio-button label="框架" />
                    <el-radio-button label="数据" />
                  </el-radio-group>
                </div>
                <el-button
                  size="mini"
                  type="text"
                  title="点击自动调研框架"
                  :loading="topicpromptgenerateloading"
                  @click="handleAutoGetArticlePrompt"
                >开始调研</el-button>
              </el-form-item>
              <el-form-item label="keyword">
                <el-row>
                  <el-col :span="18">
                    <el-input v-model="topicTemp.keyword" type="textarea" :rows="2" style="max-width: 500px" placeholder="关键词,搜索量,难度(每行一个)" />
                    <!--                          <el-popover-->
                    <!--                            placement="top-start"-->
                    <!--                            title="提示"-->
                    <!--                            width="400"-->
                    <!--                            trigger="hover"-->
                    <!--                            >-->
                    <!--                             <el-alert-->
                    <!--                              title="单独[keyword]模板"-->
                    <!--                              type="success"-->
                    <!--                              description="[keyword]代表关键词例如:How to Make [keyword] ?"-->
                    <!--                              >-->
                    <!--                            </el-alert>-->
                    <!--                             <el-alert-->
                    <!--                              title="vs两两对比"-->
                    <!--                              type="warning"-->
                    <!--                              description="[k1],[k2]代替第一个和第二个关键词例如:[k1] vs [k2] How to choose?;注意此模式下每行一个关键词，不能有流量和难度数据"-->
                    <!--                             >-->
                    <!--                            </el-alert>-->
                    <!--                             <el-alert-->
                    <!--                              title="AI标题"-->
                    <!--                              type="error"-->
                    <!--                              description="填入:ai_title即可">-->
                    <!--                            </el-alert>-->
                    <!--                            <el-input slot="reference" size="mini" v-model="topicTemp.title_template" placeholder="template[keyword]"></el-input>-->
                    <!--                    </el-popover>-->
                  </el-col>
                  <el-col :span="6">
                    搜索量<el-input v-model="topicTemp.volume" size="mini" style="width: 100px" /><br>
                    难度<el-input v-model="topicTemp.difficulty" size="mini" style="width: 100px" />
                    <!--                唯一<el-switch-->
                    <!--                  v-model="website_unique"-->
                    <!--                  active-color="#13ce66"-->
                    <!--                  inactive-color="#ff4949">-->
                    <!--                </el-switch>-->
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="title">
                <el-row>
                  <el-col>
                    <el-input v-model="topicTemp.title" size="mini" style="width: 100%" />
                    <el-alert v-if="topicTemp.keyword.split('\n').length > 1 && topicTemp.title !== ''" type="warning" title="批量添加，请清空关键词" />
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="内容">
                <!--          <tinymce ref="mt" :height="300" v-model="topicTemp.description"></tinymce>-->
                <!--          <simplemde-md :id="md_id" :value="topicTemp.description" placeholder="markdown标记" style="display: block"></simplemde-md>-->
                <!--              <el-input style="max-height: 400px" type="textarea" rows="10" v-model="topicTemp.description" placeholder="# 一级标题 ## 二级标题 注意#号于内容质检有个空格"></el-input>-->
                <v-md-editor
                  ref="mdEditor"
                  v-model="topicTemp.description"
                  height="400px"
                  :disabled-menus="['image',
                                    'code',
                                    'bold',
                                    'italic',
                                    'strike',
                                    'line',
                                    'quote',
                                    'list',
                                    'ordered-list',
                                    'check',
                                    'install',
                                    'link']"
                  class="section-alternating-editor"
                  placeholder="# 一级标题 ## 二级标题 注意#号于内容之间有个空格"
                  @change="handleEditorChange"
                  @input="handleInput"
                />
                <el-alert v-if="topicTemp.description.indexOf('# 一级标题') !== -1" type="warning" title="!初始内容未删除,模板不会处理" />
              </el-form-item>
              <el-form-item label="框架类型:">
                <el-row>
                  <el-col :span="8">优化类型:
                    <el-select v-model="topicTemp.category_id" placeholder="优化类型" size="mini" class="head" clearable>
                      <el-option
                        v-for="category in categories"
                        :key="category.id"
                        :label="category.name"
                        :value="category.id"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="8">
                    文章类型:
                    <el-select v-model="topicTemp.strategy_id" placeholder="文章类型" size="mini" class="head" clearable>
                      <el-option
                        v-for="strategy in strategies"
                        :key="strategy.id"
                        :label="strategy.name"
                        :value="strategy.id"
                      />
                    </el-select>
                  </el-col>
                  <!--                   <el-col :span="8">-->
                  <!--                   AI:-->
                  <!--                   <el-select v-model="topicTemp.ai_writer" placeholder="AI类型" size="mini" class="head" clearable>-->
                  <!--                    <el-option-->
                  <!--                      v-for="item in ai_writers"-->
                  <!--                      :key="item.value"-->
                  <!--                      :label="item.label"-->
                  <!--                      :value="item.value">-->
                  <!--                    </el-option>-->
                  <!--                  </el-select>-->
                  <!--               <el-popconfirm-->
                  <!--                 v-if="this.topicEditId"-->
                  <!--                  title="确定用AI利基创建博客内容吗？">-->
                  <!--                  <el-button slot="reference" @click="handleOpenAiWrite(topicTemp)" :v-loading="aiwriteloading">openAI</el-button>-->
                  <!--               </el-popconfirm>-->
                  <!--               <el-popover-->
                  <!--                  placement="top-start"-->
                  <!--                  title="提示"-->
                  <!--                  width="400"-->
                  <!--                  trigger="hover"-->
                  <!--                  >-->
                  <!--                   <el-alert-->
                  <!--                    title="自动AI"-->
                  <!--                    type="success"-->
                  <!--                    description="使用AI自动化进行"-->
                  <!--                    >-->
                  <!--                  </el-alert>-->
                  <!--                   <el-alert-->
                  <!--                    title="随机内容"-->
                  <!--                    type="warning"-->
                  <!--                    description="随机创建通过网络搜索内容，进行片段组合"-->
                  <!--                   >-->
                  <!--                  </el-alert>-->
                  <!--                  <el-alert-->
                  <!--                    title="混合内容"-->
                  <!--                    type="warning"-->
                  <!--                    description="随机片段内容+AI内容混合体"-->
                  <!--                   >-->
                  <!--                  </el-alert>-->
                  <!--                  <el-icon slot="reference" size="mini" class="el-icon-info"></el-icon>-->
                  <!--                </el-popover>-->
                  <!--                 </el-col>-->
                  <el-col :span="8">
                    段落:
                    <el-input v-model="topicTemp.ai_paragraph" style="width: 70%" title="输入相同段落数量" size="mini" placeholder="段落数量" />
                  </el-col>

                </el-row>
              </el-form-item>
              <el-form-item label="其他参数">
                <el-row>
                  <!--                <span>推广/tag:<el-input size='mini' v-model="topicTemp.tag" style="width: 200px"></el-input></span>-->
                  输出博客:
                  <el-select v-model="topicTemp.web_id" size="mini" placeholder="输出站点" clearable filterable :loading="websLoading" style="width: 300px;">
                    <el-option
                      v-for="web in webs"
                      :key="web.id"
                      :label="web.url"
                      :value="web.id"
                    />
                  </el-select>
                  写手:
                  <el-select v-model="topicTemp.writer_id" size="mini" placeholder="指定写手" filterable clearable style="width: 150px;">
                    <el-option label="不指定" value="" />
                    <el-option
                      v-for="user in users"
                      :key="user.id"
                      :label="user.show_name"
                      :value="user.id"
                    />
                  </el-select>
                </el-row>
                <el-row style="margin-top: 10px" :gutter="40">
                  <!--            <el-col :span="6">-->
                  <!--               amazon:<el-switch-->
                  <!--                  v-model="topicTemp.is_crawl_amazon"-->
                  <!--                  active-color="#13ce66"-->
                  <!--                  inactive-color="#ff4949">-->
                  <!--                </el-switch>-->
                  <!--             </el-col>-->
                  <!--                <el-col :span="6">-->
                  <!--                   爬取素材:<el-switch-->
                  <!--                        v-model="topicTemp.serp_crawl"-->
                  <!--                        active-color="#13ce66"-->
                  <!--                        inactive-color="#ff4949">-->
                  <!--                      </el-switch>-->
                  <!--                  <span style="margin-left: 10px">完成:</span><el-switch-->
                  <!--                        v-model="topicTemp.serp_finished"-->
                  <!--                        active-color="#13ce66"-->
                  <!--                        inactive-color="#ff4949">-->
                  <!--                      </el-switch>-->
                  <!--                </el-col>-->
                  <el-col :span="12">
                    <div>
                      <span>进度:</span>
                      <el-input slot="reference" v-model="topicTemp.progress" style="width: 150px; display: inline-block; margin-left: 10px" size="mini" type="number" />
                      <el-popover
                        placement="top-start"
                        title="提示"
                        width="400"
                        trigger="hover"
                      >
                        <el-alert
                          title="进度小于5"
                          type="success"
                          description="自动化AI必须小于5才会进行自动编辑，大于5的内容不会进入自动化"
                        />
                        <el-alert
                          title="91-99"
                          type="warning"
                          description="作为自定义优先级配合使用"
                        />
                        <el-icon slot="reference" size="mini" class="el-icon-info" />
                      </el-popover>
                      <!--               <el-slider-->
                      <!--                 style="width: 200px;display: inline-block; margin: auto;"-->
                      <!--                v-model="topicTemp.progress"-->
                      <!--                 @change="handleSearch"-->
                      <!--                :max="100">-->
                      <!--              </el-slider>-->
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <el-button type="text" @click="handleClickPublish">自动发布设置</el-button>
                    <el-tag v-if="topicTemp.auto_post_account_id">wp账号:{{ topicTemp.auto_post_account_id }}|{{ post_domain }}</el-tag>
                    <el-tag v-if="topicTemp.auto_post_category">目录id:{{ topicTemp.auto_post_category }} </el-tag>
                    <el-tag v-if="topicTemp.auto_post_tags">tag:{{ topicTemp.auto_post_tags }} </el-tag>
                  </el-col>

                </el-row>
              </el-form-item>
            </el-form>
            <el-row :gutter="20" style="margin-left: auto;margin-right: 0; text-align: center;">
              <el-button v-if="topicViewData.post_id" type="danger" style="display: inline-block" @click="handleRewrite()">重写</el-button>
              <el-button style="display: inline-block" @click="handleCleanTopicForm">清空内容</el-button>
              <el-button style="display: inline-block" @click="titleTopicDialogVisible = false">取 消</el-button>
              <el-dropdown :loading="saveTopicLoading" split-button type="success" @click="handleCheckAddTopic()">
                保 存
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native.stop="handleCheckAddTopic('aiwrite')">保存并开始写内容</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </el-col>
        </el-row>
      </div>
      <!-- 折叠/展开按钮，始终可见 -->
      <el-button
        type="text"
        :icon="showMaterial ? 'el-icon-arrow-left' : 'el-icon-arrow-right'"
        circle
        style="position: absolute; top: 10px; right: 100px;"
        @click="toggleMaterial"
      >
        {{ showMaterial ? '隐藏素材' : '显示素材' }}
      </el-button>
      <span slot="footer" class="dialog-footer">
        <!--            <el-button style="float: left" @click="handleShowMaterial()">查看素材</el-button>-->

      </span>
    </el-drawer>

    <el-dialog
      :title="titleTopicViewDialog"
      :visible.sync="TopicViewDialogVisible"
      style="margin-top: 10px !important;"
    >
      <h3>{{ topicViewData.title }}</h3>
      <hr>
      <div style="display: block; font-size: 14px;max-height: 438px" v-html="topicViewData.description" />

      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="HanldeEditTopic">编 辑</el-button>
        <el-button @click="TopicViewDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!--    <el-drawer-->
    <!--      :title="topic_title"-->
    <!--      :visible.sync="topicmaterialDrawerVisible"-->
    <!--      :wrapperClosable = 'false'-->
    <!--      @close="materialVisible=false"-->
    <!--      direction="rtl">-->
    <!--      <topicmaterial :topic_id="topic_id" :topic_title="topic_title" :webVisible="materialVisible"-->
    <!--                   @closeMetrialDialog="materialVisible=false"></topicmaterial>-->
    <!--    </el-drawer>-->
    <el-dialog
      :title="postsdataDialogTitle"
      :visible.sync="postsdataDialogVisible"
      style="margin-top: 148px !important;"
    >
      <el-table :data="postsdata">
        <el-table-column align="center" label="title" prop="title">
          <template slot-scope="scope"><a :href="scope.row.post_url" target="_blank">{{ scope.row.title }}</a></template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="postsdataDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <topicpost
      :topic_id="topic_id"
      :topic_title="topic_title"
      :web-visible="postVisible"
      @closeMetrialDialog="postVisible=false"
    />
    <web :web-visible="webVisible" @reload="handleFetchWebs" @closeWebDialog="webVisible=false" />
    <post_editor :post_id="edit_post_id" :post-editor-visible="postEditorVisible" @close="postEditorVisible=false" />
    <wppromote
      :promote-visiable="promoteVisiable"
      @save="handleSaveAutoPostInfo"
      @closewppromoteDialog="promoteVisiable=false"
    />
    <openaidialog :visible="openaiDialogVisible" :title="topicTemp.title" :keyword="topicTemp.keyword" @close="openaiDialogVisible=false" />
    <children_topics_editor :progress="progress" :stars="stars" :title="operate_title" :parent_id="id" :is-visible="childTopicsEditorVisible" @close="childTopicsEditorVisible=false" />
    <aiprompt :is-visible="aipromptVisible" app="" @closeDialog="aipromptVisible=false" @insert="handleInsertShortCode" />

    <!-- Topic 数据分析窗口 -->
    <TopicAnalysisV2
      :visible.sync="topicAnalysisVisible"
      :topic-data="topicTemp"
      @saved="handleTopicAnalysisSaved"
      @close="topicAnalysisVisible = false"
    />

  </div>
</template>

<script>
import { Get as Getstrategies } from '@/api/cms/topicstrategy'
import { Get as GetCategories } from '@/api/cms/category'
import { Get as GetWPAccount } from '@/api/cms/wpaccount'
import { GetWPPostStatistics } from '@/api/cms/wppost'
import { Put, Delete, Post as AddTopic, Tree as GetTopics, topic_crawl_amazon_toggle } from '@/api/cms/topic'
import { CRMGetProjectUsers } from '@/api/crm/crmmanage'
import clip from '@/utils/clipboard' // use clipboard directly
import topicmaterial from '@/views/cms/elements/topicmaterial'
import topicpost from '@/views/cms/elements/topicpost'
import { Get as GetWebs } from '@/api/cms/web'
import { AIGenerateTopicPrompt } from '@/api/crm/crmai'
// import Tinymce from '@/components/Tinymce'
import qs from 'qs'
import AITask from '@/components/AITask'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

import Cookies from 'js-cookie'
import Web from './elements/web'
import Post_editor from './elements/posteditor'
import Wppromote from './elements/wppromote'
import { WritePost as OpenAiWritePost } from '../../api/cms/openai'
import Openaidialog from './elements/openaidialog'
import Children_topics_editor from './elements/children_topics_editor'
import { Get as GetWpAccounts } from '@/api/cms/wpaccount'
import { SelectText } from './topiclist'
import Aicontent from '../../components/aicontent'
import Aiprompt from './elements/aiprompt'
import TopicAnalysisV2 from '@/components/TopicAnalysisV2'
// import SimplemdeMd from "../../components/MarkdownEditor/index";

const ProjectKey = 'cms_project_id__search'
const StrotegyKey = 'cms_strategy_id__search'
const TopicKeywordKey = 'cms__keyword__search'
const OwnerKey = 'cms_language_id__owner'
const webIdKey = 'cms_web_id'
export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function getTokenStr(key) {
  const v = Cookies.get(key)
  return v || null
}

export function setToken(key, value) {
  if (value) {
    return Cookies.set(key, value)
  }
}

export default {
  components: { Aiprompt, Aicontent, Children_topics_editor, Openaidialog, Wppromote, Post_editor, Web, topicmaterial, topicpost, AITask, TopicAnalysisV2 },
  data() {
    return {
      editor: '',
      aipromptVisible: false,
      topicAnalysisVisible: false,
      accountAlertTitle: '',
      wpaccont_domian: '',
      postsdataDialogTitle: '查询已发帖',
      postsdataDialogVisible: false,
      postsdata: [],
      poststotal: 0,
      openaiDialogVisible: false,
      ai_writers: [
        {
          label: '付费AI',
          value: 'openai'
        },
        {
          label: '免费AI',
          value: 'autoai'
        },
        {
          label: '不自动',
          value: ''
        }

      ],
      promoteVisiable: false,
      filterText: '',
      parent_id: '',
      edit_post_id: '',
      postEditorVisible: false,
      md_id: 1,
      progress: [0, 100],
      stars: [1, 5],
      star: 1,
      drawer_data: [],
      drawer: false,
      activeToolName: '1',
      topicMateiralTemp: {
        title: '',
        note: ''
      },
      postVisible: false,
      materialVisible: true,
      topicmaterialDrawerVisible: false,
      // titleTopicMaterialDialog: '',
      // titleTopicMaterialDialogVisible: false,
      intopic_materialVisible: true,
      topic_id: '',
      drawer_size: '90%',
      topic_title: '框架素材',
      dataMaterial: [],
      TopicViewDialogVisible: false,
      showMaterial: false,
      titleTopicViewDialog: '查看内容',
      generateresponse: '',
      topicViewData: {
        crawl_count: 0,
        title: '',
        description: '',
        tag: '',
        strategy_id: '',
        keyword: '',
        progress: 0
      },
      topicEditId: '',
      titleTopicDialog: '添加新框架',
      titleTopicDialogVisible: false,
      saveTopicLoading: false,
      expanded_ids: [],
      categories: [],
      aiwriteloading: false,
      website_unique: false,
      post_domain: '',
      activeOptionsName: 'first',
      get_later: false,
      generate_type: '框架',
      topicpromptgenerateloading: false,
      topicTemp: {
        ai_writer: 'openai',
        title_template: '',
        category_id: '3', // 文章类型
        parent_id: '',
        crawl_count: 0,
        title: '',
        star: 1,
        ai_paragraph: 1,
        is_crawl_amazon: false,
        web_id: '',
        serp_crawl: false,
        serp_finished: false,
        project_id: this.$store.getters.projectId,
        description: '',
        tag: '',
        strategy_id: '',
        auto_post_account_id: '',
        auto_post_category: '',
        auto_post_tags: '',
        keyword: '',
        difficulty: 30,
        volume: 0,
        progress: 0,
        writer_id: ''
      },
      listLoading: false,
      webVisible: false,
      projectsLoading: false,

      strategies: [],
      strategy_id: null,
      strategysLoading: false,

      languages: [],
      language_id: null,
      languagesLoading: false,

      users: [],
      owner_id: null,
      ownersLoading: false,

      webs: [],
      web_id: '',
      websLoading: false,

      title: '',
      content: '',
      saveDisabled: false,
      init_text: '',
      operate_title: '',
      kwInput: '',
      TagInput: '',
      keyword: '',
      volume: '',
      difficulty: '',
      id: '',
      childTopicsEditorVisible: false,
      more_filter: false,
      data: [],
      order_by: 'id',
      order_desc: '1',
      // pagination
      pagesize: 20,
      page: 1,
      total: 0,

      m_active: false,
      search_parent_id: '',
      current_expended_node: null,
      deleteDialogVisible: false,
      deleteDialogTitle: '',
      deleteId: null,
      loaddata: [],
      deleteRow: null,
      deleteDialogLoading: false,
      aiTitleAnalysisDialogVisible: false,
      aiTitleAnalysisLoading: false,
      aiTitleAnalysisResult: ''
    }
  },
  computed: {
    aiStatusMessage() {
      if (!this.topicViewData || this.topicViewData.crawl_count === undefined) {
        return '等待开始调研...'
      }
      const status = this.topicViewData.crawl_count

      switch (status) {
        case 0:
          return '等待开始调研 建议SOP 调研框架->人工调整框架->调研数据->AI写内容'
        case 1:
          return '正在调研框架中，请稍等...'
        case 2:
          return '已提交后台正在调研数据中，可以关闭此页面等待 2分钟左右再来查看或者查看钉钉群通知'
        case 3:
          return '已提交后台正在调研框架和数据中，可以关闭此页面等待 2分钟左右再来查看或者查看钉钉群通知'
        case 4:
          return '已提交后台AI正在写作中，可以关闭此页面等待几分钟左右再来查看或者查看钉钉群通知'
        case 11:
          return '框架调研已完成'
        case 12:
          return '数据调研已完成'
        case 13:
          return '框架和数据调研都已完成'
        case 14:
          return 'AI写作已完成'
        default:
          return '状态未知'
      }
    },
    projects() {
      console.log(this.$store.getters.projects)
      return this.$store.getters.projects
    }
  },
  watch: {
    'topicTemp.description': {
      handler(newVal) {
        this.$nextTick(() => {
          this.applyAlternatingStyles()
        })
      },
      immediate: true // 首次加载时也执行
    },
    filterText(val) {
      this.$refs.TopicTree.filter(val)
    },
    project_id(newValue, oldValue) {
      if (newValue !== oldValue) {
        // 当 projectId 改变时执行的操作
        console.log('项目发送改变')
        this.getList()
      }
    }

  },
  created() {
    this.$nextTick(() => {
      if (this.editor) {
        this.applyAlternatingStyles()
      }
    })
    if (this.$route.query.pid) {
      this.search_parent_id = this.$route.query.pid
      this.expanded_ids = [this.parent_id]
    }
    this.materialVisible = true
    this.project_id = this.$store.getters.projectId
    console.log(this.project_id)
    // this.strategy_id = getToken(StrotegyKey)
    this.owner_id = getToken(OwnerKey)
    // this.keyword = getTokenStr(TopicKeywordKey)
    this.web_id = getToken(webIdKey)
    this.topicTemp.web_id = getToken(webIdKey)
    this.topicTemp.project_id = this.project_id || ''
    // this.handleFetchProjects()
    this.handleFetchWebs()
    this.handleFetchstrategies()
    this.handleFetchGetUsers()
    this.handleFetchCategories()
    if (this.web_id) {
      this.getList()
    }

    this.materialVisible = false
  },
  methods: {
    // 验证搜索量输入
    validateVolume() {
      if (this.topicTemp.volume !== null && this.topicTemp.volume !== undefined && this.topicTemp.volume !== '') {
        const value = Number(this.topicTemp.volume)
        if (isNaN(value) || value < 0) {
          this.topicTemp.volume = 0
          this.$message.warning('搜索量必须是非负数字')
        }
      }
    },

    // 验证难度输入
    validateDifficulty() {
      if (this.topicTemp.difficulty !== null && this.topicTemp.difficulty !== undefined && this.topicTemp.difficulty !== '') {
        const value = Number(this.topicTemp.difficulty)
        if (isNaN(value) || value < 0) {
          this.topicTemp.difficulty = 0
          this.$message.warning('难度必须是0-100之间的数字')
        } else if (value > 100) {
          this.topicTemp.difficulty = 100
          this.$message.warning('难度不能超过100')
        }
      }
    },

    // 验证进度输入
    validateProgress() {
      if (this.topicTemp.progress !== null && this.topicTemp.progress !== undefined && this.topicTemp.progress !== '') {
        const value = Number(this.topicTemp.progress)
        if (isNaN(value) || value < 0) {
          this.topicTemp.progress = 0
          this.$message.warning('进度必须是0-100之间的数字')
        } else if (value > 100) {
          this.topicTemp.progress = 100
          this.$message.warning('进度不能超过100')
        }
      }
    },

    // 验证搜索框的搜索量
    validateSearchVolume() {
      if (this.volume !== null && this.volume !== undefined && this.volume !== '') {
        const value = Number(this.volume)
        if (isNaN(value) || value < 0) {
          this.volume = null
          this.$message.warning('搜索量必须是非负数字')
        }
      }
    },

    // 验证搜索框的难度
    validateSearchDifficulty() {
      if (this.difficulty !== null && this.difficulty !== undefined && this.difficulty !== '') {
        const value = Number(this.difficulty)
        if (isNaN(value) || value < 0) {
          this.difficulty = null
          this.$message.warning('难度必须是0-100之间的数字')
        } else if (value > 100) {
          this.difficulty = 100
          this.$message.warning('难度不能超过100')
        }
      }
    },
    // 打开 Topic 分析窗口
    handleShowTopicAnalysis() {
      console.log('handleShowTopicAnalysis - topicTemp:', this.topicTemp)
      console.log('handleShowTopicAnalysis - topicTemp.id:', this.topicTemp.id)

      if (!this.topicTemp.id) {
        this.$message.warning('请先保存话题后再进行分析')
        return
      }
      this.topicAnalysisVisible = true
    },
    // Topic 分析结果保存后的回调
    handleTopicAnalysisSaved(data) {
      this.$message.success('分析结果已保存')
      console.log('分析结果:', data)
    },

    handleInput() {
      this.$nextTick(() => {
        this.applyAlternatingStyles()
      })
    },

    applyAlternatingStyles() {
      const editor = this.$refs.mdEditor
      if (!editor) return

      // 获取编辑器的 pre 元素下的所有 section
      const editorElement = editor.$el.querySelector('.v-md-textarea-editor pre')
      if (!editorElement) return

      const sections = editorElement.querySelectorAll('section')
      let isEvenSection = false

      sections.forEach((section, index) => {
        // 移除已有的样式类
        section.classList.remove('section-odd', 'section-even', 'section-header')

        // 获取文本内容
        const content = section.textContent || ''

        // 检查是否是标题行
        if (content.trim().startsWith('## ')) {
          isEvenSection = !isEvenSection
          section.classList.add('section-header')
        }

        // 添加奇偶样式
        section.classList.add(isEvenSection ? 'section-even' : 'section-odd')
      })
    },
    handleEditorChange(text) {
      this.topicTemp.description = text
      console.log('chagneed !!!!!')
      this.applyAlternatingStyles()
    },
    getAiStatusTag(status) {
      switch (status) {
        case 1:
          return '调研框架中'
        case 2:
          return '调研数据中'
        case 3:
          return '调研中'
        case 4:
          return 'AI写作中'
        case 11:
          return '框架调研已完成'
        case 12:
          return '数据调研已完成'
        case 13:
          return '框架和数据调研都已完成'
        case 14:
          return 'AI写作已完成'
        default:
          return '状态未知'
      }
    },
    updateTreeNode(data, id, newData) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === id) {
          // Update the node with new data while preserving reactivity
          Object.keys(newData).forEach(key => {
            if (newData[key] !== undefined) {
              this.$set(data[i], key, newData[key])
            }
          })
          return true
        }
        if (data[i].children && data[i].children.length > 0) {
          if (this.updateTreeNode(data[i].children, id, newData)) {
            return true
          }
        }
      }
      return false
    },
    toggleMaterial() {
      this.showMaterial = !this.showMaterial
    },
    handleAutoGetArticlePrompt(type) {
      if (type === '框架') {
        this.generate_type = '框架'
      } else if (type === '数据') {
        this.generate_type = '数据'
      }
      if (this.topicTemp.title.length === 0) {
        this.$message.error('请先修改标题')
        return
      }
      if (this.topicTemp.id === 0) {
        this.$message.error('请先保存框架')
        return
      }
      this.$confirm('确定执行自动获取框架或者数据,此操作会消耗费用？', '执行获取框架', {
        confirmButtonText: '确定执行',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        if (this.generate_type === '框架') {
          this.get_later = false
        } else {
          this.get_later = true
        }
        this.callAIGenerateTopicPrompt()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    callAIGenerateTopicPrompt() {
      this.generateresponse = ''
      this.topicpromptgenerateloading = true
      if (this.generate_type === '框架') {
        this.topicViewData.crawl_count = 1
      } else if (this.generate_type === '数据') {
        this.topicViewData.crawl_count = 2
      } else if (this.generate_type === '都调研') {
        this.topicViewData.crawl_count = 3
      }
      AIGenerateTopicPrompt({
        topic_id: this.topicTemp.id,
        generate_type: this.generate_type,
        get_later: this.get_later
      })
        .then(response => {
          if (response.data.indexOf('后台生成中') !== -1) {
            this.generateresponse = response.data
          } else {
            this.topicTemp.description = response.data
          }

          this.topicpromptgenerateloading = false
          // 提示后台执行中，等待结果再刷新
          this.$message({
            type: 'success',
            message: '已经提交生成请求，可以关闭界面，钉钉会提醒结果'
          })
        })
        .catch(e => {
          console.error(e)
          this.topicpromptgenerateloading = false
        })
    },
    handleInsertShortCode(shortcode) {
      console.log(shortcode)
      this.aipromptVisible = false
    },
    openAiSuccessCBK(content) {
      this.topicTemp.description = content
    },
    handleGetWPPostStatics() {
      if (this.web_id === '') {
        return
      }
      const filter_webs = this.webs.filter(item => item.id === this.web_id)
      if (filter_webs && filter_webs.length) {
        this.wpaccont_domian = filter_webs[0].url
      }
      if (this.wpaccont_domian.length) {
        GetWPPostStatistics({
          domain: this.wpaccont_domian
        })
          .then(response => {
            let msg = '已经发帖数量:\n'
            const keys = Object.keys(response.data)
            for (let i = 0; i < keys.length; i++) {
              msg += keys[i] + ':' + response.data[keys[i]] + '比例:' + parseInt(response.data[keys[i]] * 100 / response.total) + '%\n'
            }
            alert(msg)
          }).catch(err => {
            console.log(err)
          })
      }
    },
    handleSearchWPAccount() {
      this.accountAlertTitle = ''
      if (this.web_id === '') {
        return
      }
      const filter_webs = this.webs.filter(item => item.id === this.web_id)
      if (filter_webs && filter_webs.length) {
        this.wpaccont_domian = filter_webs[0].url
      }
      this.getList()
      if (this.wpaccont_domian.length) {
        GetWPAccount(null, qs.stringify({
          kw: this.wpaccont_domian,
          auto_blog: false,
          pagesize: 1,
          page: 1
        }))
          .then(response => {
            if (response.data.data && response.data.data.length && response.data.data[0].daily_days) {
              const need_posts = response.data.data[0].daily_days * response.data.data[0].daily_post
              if (response.data.data[0].waiting_posts < need_posts) {
                // this.accountAlertTitle = '每' + response.data.data[0].daily_days + '天发帖:' + response.data.data[0].daily_days + ' 可发贴:' + response.data.data[0].waiting_send + '周期内已发:' + response.data.data[0].today_post
                this.accountAlertTitle = '内容不足，需要添加更多框架. 可优化:' + response.data.data[0].waiting_posts + '可发:' + response.data.data[0].waiting_send + '周期内已发:' + response.data.data[0].today_post + ' 每' + response.data.data[0].daily_days + '天需要发帖:' + response.data.data[0].daily_post + '[数据每小时更新一次]'
              }
            }
          }).catch(err => {
            console.log(err)
          })
      }
    },
    handleGetClickText() {
      const keyword = SelectText()
      if (keyword.length > 0) {
        this.GetPostedTopics(keyword)
      }
    },
    GetPostedTopics(keyword) {
      this.poststotal = 0
      GetTopics(null, qs.stringify({
        kw: keyword,
        progress_s: 100,
        progress_e: 100,
        pagesize: this.pagesize,
        page: this.page,
        star: this.star,
        order_by: this.order_by,
        order_desc: this.order_desc,
        owner_id: this.owner_id,
        project_id: this.project_id,
        web_id: this.web_id,
        strategy_id: this.strategy_id
      }))
        .then(response => {
          this.postsdata = response.data.data.map(m => {
            this.$set(m, 'active', false)
            return m
          })
          if (this.postsdata.length === 0) {
            this.$message.warning(keyword + '没有匹配数据')
          } else {
            this.postsdataDialogTitle = keyword + '已经发帖' + response.data.total + '篇'
            this.postsdataDialogVisible = true
          }
        }).catch(e => {
          this.$message.error(keyword + '查询数据失败')
        })
    },
    handleGetWpaccount(id) {
      GetWpAccounts(id, null)
        .then(response => {
          this.post_domain = response.data.domain
        })
        .catch(e => {
          console.log('get domain failed')
          this.post_domain = ''
        })
    },
    handleFetchCategories() {
      GetCategories()
        .then(response => {
          this.categories = response.data.data
          this.topicTemp.category_id = 3
        })
        .catch(e => {
          this.$message.error('获取文章类型失败')
        })
    },
    append(data) {
      // console.log(data)
      // topicViewData 复制data内容
      Object.keys(data).forEach(key => {
        if (data[key] !== undefined) this.topicViewData[key] = data[key]
      })
      // this.topicViewData.id = data.id
      // this.topicViewData.description = ''
      this.topicViewData.title = ''
      this.copydata()
      this.topicTemp.parent_id = data.id
      delete this.topicTemp.id
      delete this.topicViewData.id
      // console.log('modify append id to null')
      this.topicTemp.progress = 0
      this.title = ''
      this.keyword = ''
      this.titleTopicDialog = '父框架:' + data.keyword + 'ID:' + this.topicTemp.parent_id + '》添加子框架'
      this.drawer_size = '1200px'
      // 删除topicviewdata的id
      // delete this.topicViewData.id
      this.handleAddNewTopic()
    },
    showAddNewTopic() {
      this.topicTemp.parent_id = ''
      this.topicTemp.id = ''
      this.titleTopicDialog = '添加新顶级框架'
      this.title = ''
      this.keyword = ''
      this.handleAddNewTopic()
    },
    remove(node, data) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },
    handleFetchWebs() {
      this.websLoading = true
      GetWebs()
        .then(response => {
          this.websLoading = false
          this.webs = response.data.data
          if (this.webs.length) {
            this.web_id = getToken(webIdKey) || this.webs[0].id
            this.handleSearchWPAccount()
          }
        })
        .catch(e => {
          this.websLoading = false
        })
    },
    changeWPAccount(v) {
      this.web_id = v
    },
    // handleFetchProjects() {
    //   this.projectsLoading = true
    //   GetProjects()
    //     .then(response => {
    //       this.projectsLoading = false
    //       this.projects = response.data.data
    //       if (this.projects.length) {
    //         this.project_id = getToken(ProjectKey) || null
    //       }
    //     })
    //     .catch(e => {
    //       this.projectsLoading = false
    //     })
    // },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleFetchstrategies() {
      this.strategysLoading = true
      this.strategy_id = ''
      Getstrategies(null, qs.stringify({ project_id: this.project_id }))
        .then(response => {
          this.strategysLoading = false
          this.strategies = response.data.data
        })
        .catch(e => {
          this.strategysLoading = false
        })
    },
    handleFetchGetUsers() {
      this.ownersLoading = true
      CRMGetProjectUsers(qs.stringify({
        pagesize: 100,
        page: 1,
        order_by: this.order_by,
        order_desc: this.order_desc
      })).then(response => {
        this.ownersLoading = false
        this.users = response.data.data
        if (this.users.length) {
          this.owner_id = getToken(OwnerKey) || null
        }
      })
        .catch(e => {
          this.ownersLoading = false
        })
    },
    getList(loading) {
      if (loading === undefined) {
        loading = true
      }
      if (this.web_id === '' || this.web_id === null) {
        this.$message.error('树形结构必须选择网站')
        return
      }
      this.listLoading = loading
      GetTopics(null, qs.stringify({
        kw: this.kwInput,
        parent_id: this.search_parent_id,
        progress_s: this.progress[0],
        progress_e: this.progress[1],
        keyword: this.keyword,
        star: this.star,
        min_star: this.stars[0],
        max_star: this.stars[1],
        tag: this.TagInput,
        min_volume: this.volume,
        max_diff: this.difficulty,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc,
        owner_id: this.owner_id,
        project_id: this.project_id,
        web_id: this.web_id,
        id: this.id,
        strategy_id: this.strategy_id
      }))
        .then(response => {
          this.scrollTop()
          // setToken(StrotegyKey, this.strategy_id)
          setToken(OwnerKey, this.owner_id)
          setToken(TopicKeywordKey, this.keyword)
          setToken(webIdKey, this.web_id)
          this.data = response.data.data.map(m => {
            this.$set(m, 'active', false)
            return m
          })
          if (this.search_parent_id && response.data.parent) {
            this.current_expended_node = response.data.parent
          }
          if (this.id && this.data.length) {
            this.current_expended_node = this.data[0]
          }
          this.listLoading = false
          if (this.keyword) {
            this.total = response.data.data[0]['children_count']
          } else {
            this.total = response.data.total
          }
          this.drawer_data = this.data
        }).catch(e => {
          this.listLoading = false
          setToken(ProjectKey, this.project_id)
          setToken(StrotegyKey, this.strategy_id)
          setToken(OwnerKey, this.owner_id)
          setToken(TopicKeywordKey, this.keyword)
        })
    },
    handleAddNewTopic() {
      this.topicEditId = ''
      this.topic_id = ''
      this.topicTemp.keyword = ''
      this.topicTemp.id = ''
      this.titleTopicDialogVisible = true
      if (this.topicTemp.auto_post_account_id !== '') {
        this.handleGetWpaccount(this.topicTemp.auto_post_account_id)
      }
      // this.handleCleanTopicForm()
    },
    copydata() {
      this.topicTemp.ai_writer = this.topicViewData.ai_writer
      this.topicTemp.title = this.topicViewData.title
      this.topicTemp.parent_id = this.topicViewData.parent_id
      this.topicTemp.keyword = this.topicViewData.keyword
      this.topicTemp.volume = this.topicViewData.volume
      this.topicTemp.difficulty = this.topicViewData.difficulty
      this.topicTemp.tag = this.topicViewData.tag
      this.topicTemp.ai_paragraph = this.topicViewData.ai_paragraph
      this.topicTemp.star = this.topicViewData.star
      this.topicTemp.description = this.topicViewData.description
      this.topicTemp.crawl_count = this.topicViewData.crawl_count
      this.topicTemp.ai_prompte_finished = this.topicViewData.ai_prompte_finished
      this.topicTemp.progress = this.topicViewData.progress
      this.topicTemp.project_id = this.topicViewData.project_id
      this.topicTemp.web_id = this.topicViewData.web_id
      this.topicTemp.category_id = this.topicViewData.category_id
      this.topicTemp.auto_post_account_id = this.topicViewData.auto_post_account_id
      this.topicTemp.auto_post_category = this.topicViewData.auto_post_category
      this.topicTemp.auto_post_tags = this.topicViewData.auto_post_tags
      this.topicTemp.serp_finished = this.topicViewData.serp_finished
      this.topicTemp.is_crawl_amazon = this.topicViewData.is_crawl_amazon
      this.topicTemp.serp_crawl = this.topicViewData.serp_crawl
      this.topicTemp.writer_id = this.topicViewData.writer_id
      this.topicTemp.strategy_id = this.topicViewData.strategy_id
    },
    HanldeEditTopic() {
      this.topicEditId = this.topicViewData.id
      this.titleTopicDialog = '编辑框架-ID:' + this.topicViewData.id + '-' + this.topicViewData.title
      this.drawer_size = '90%'
      this.TopicViewDialogVisible = false
      this.titleTopicDialogVisible = true
      if (this.topicTemp.auto_post_account_id !== '') {
        this.handleGetWpaccount(this.topicTemp.auto_post_account_id)
      }
      // this.$nextTick(() => {
      //   this.$refs.mt.setContent(this.topicTemp.description)
      // })
    },
    handleToggleAmazonCrawlStatus(row) {
      if (row.keyword === '') {
        this.$message.error('关键词为空,修改无效')
        return
      }
      topic_crawl_amazon_toggle(row.id).then(response => {
        this.$message('修改成功')
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleChangeCrawlSerp(row) {
      // console.log('progress clicked')
      this.topicEditId = row.id
      this.expanded_ids = [row.id]
      Put(this.topicEditId, { 'serp_crawl': row.serp_crawl }).then(response => {
        this.$message.success('修改成功')
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleModifyProgress(row) {
      // console.log('progress clicked')
      this.expanded_ids = [row.id]
      this.topicTemp.title = row.title
      this.topicTemp.keyword = row.keyword
      this.topicTemp.tag = row.tag
      this.topicTemp.description = row.description
      this.topicTemp.progress = row.progress
      this.topicEditId = row.id
      this.titleTopicDialog = '编辑框架-' + row.title
      this.topicTemp.strategy_id = row.strategy_id
      this.titleTopicDialogVisible = true
      // if (typeof this.$refs.mt !== 'undefined') {
      //   this.$nextTick(() => {
      //     this.$refs.mt.setContent(this.topicTemp.description)
      //   })
      // }
    },
    handleOpenAiWrite(row) {
      // console.log(row)
      let engine = 'text-curie-001'
      if (row.category_id && row.category_id === 1) {
        engine = 'text-davinci-003'
      }
      if (row.category_id && row.category_id === 3) {
        engine = 'text-babbage-001'
      }
      this.aiwriteloading = true
      OpenAiWritePost({ topic_id: this.topicEditId, engine: engine }).then(response => {
        this.$message.success('编辑成功')
        this.getList()
        this.aiwriteloading = false
      }).catch(e => {
        this.notify('编辑失败')
        this.aiwriteloading = false
      })
    },
    handleClickPublish() {
      this.promoteVisiable = true
    },
    handleSaveAutoPostInfo(value) {
      this.topicTemp.auto_post_account_id = value.account_id
      this.topicTemp.auto_post_category = ''
      const _ids = []
      for (let i = 0; i < value.categories.length; i++) {
        _ids.push(value.categories[i].name)
      }
      this.topicTemp.auto_post_category = _ids.join(',')
      this.topicTemp.auto_post_tags = value.dynamicTags.join(',')
      // console.log(this.topicTemp)
    },
    handleCopyLink(row) {
      // 复制链接到剪切板
      const baseUrl = process.env.BASE_DOMAIN || 'https://erp.kikimami.com'
      const url = `${baseUrl}/#/cms/topictree?pid=${row.id}`
      navigator.clipboard.writeText(url).then(() => {
        // 显示消息提示复制成功
        this.$message({
          message: '链接已复制到剪贴板',
          type: 'success',
          duration: 2000
        })
      }).catch(err => {
        // 错误处理
        console.error('Failed to copy: ', err)
        this.$message({
          message: '复制失败',
          type: 'error',
          duration: 2000
        })
      })
    },
    handleSaveQuickEditTopic(row, field, value) {
      // 设置row的field字段的值为value
      if (value === 'pending') {
        // 必须title和keyword都有值才能设置为pending
        if (row.title === '' || row.keyword === '') {
          this.$message.error('标题和关键词不能为空')
          return
        }
        // 已取消分类限制，任何分类都可以提交审核
      }
      const data = {
        id: row.id,
        title: row.title,
        keyword: row.keyword,
        description: row.description,
        progress: row.progress,
        volume: row.volume,
        difficulty: row.difficulty
      }
      data[field] = value
      Put(row.id, data).then(response => {
        this.$message.success('修改成功')
        // 更新成功后，确保视图更新
        this.$set(row, field, value)
        // 如果是修改 status 为 pending，更新树节点数据
        if (field === 'status' && value === 'pending') {
          this.updateTreeNode(this.data, row.id, { status: 'pending' })
        }
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleSaveTopic(row) {
      Put(row.id, row).then(response => {
        this.$message.success('修改成功')
        this.updateTreeNode(this.data, row.id, row)
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleRewrite(task) {
      if (task === 'aiwrite' && this.topicTemp.description.indexOf('aiwriter ') === -1) {
        this.$message.error('AI prompts框架不完整,请先编辑AI框架,或者点击调研数据')
        return
      }
      // 询问是否真的要重写
      this.$confirm('确定框架编辑完成', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Put(this.topicViewData.id, { 'id': this.topicViewData.id, [task]: true }).then(response => {
          this.topicViewData.ai_prompte_finished = true
          this.topicViewData.crawl_count = 4
          this.topicTemp.crawl_count = 4
          this.$message.success('修改成功')
        }).catch(e => {
          this.$message.error('修改失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    handleCheckAddTopic(extra_filed) {
      // keyword如果包含多行,但是parent_id为空,询问是否都添加到顶级目录
      if (this.topicTemp.title.indexOf('\n') !== -1 && this.topicTemp.parent_id === '') {
        this.$confirm('关键词包含多个,但是未指定父级框架,是否添加到顶级目录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleAddTopic(extra_filed)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        this.handleAddTopic(extra_filed)
      }
    },
    handleAddTopic(extra_filed) {
      // 如果keyword是批量的但是parent_id为空怎要询问是否都批量添加到顶级目录
      if (this.website_unique) {
        this.topicTemp.website_unique = this.website_unique
      }
      if (extra_filed) {
        this.topicTemp[extra_filed] = true
      } else { // 确保extra_field在topicTemp中确实存在
        // console.log('delete topicTemp extra field');
        this.$delete(this.topicTemp, 'aiwrite')
      }

      // 参数验证
      if (this.topicTemp.keyword === '') {
        this.$message.error('请输入关键词')
        return
      }

      // 验证搜索量必须是数字
      if (this.topicTemp.volume !== null && this.topicTemp.volume !== undefined && this.topicTemp.volume !== '') {
        const volume = Number(this.topicTemp.volume)
        if (isNaN(volume) || volume < 0) {
          this.$message.error('搜索量必须是非负数字')
          return
        }
        this.topicTemp.volume = volume
      } else {
        this.topicTemp.volume = 0 // 设置默认值
      }

      // 验证难度必须是数字
      if (this.topicTemp.difficulty !== null && this.topicTemp.difficulty !== undefined && this.topicTemp.difficulty !== '') {
        const difficulty = Number(this.topicTemp.difficulty)
        if (isNaN(difficulty) || difficulty < 0 || difficulty > 100) {
          this.$message.error('难度必须是0-100之间的数字')
          return
        }
        this.topicTemp.difficulty = difficulty
      } else {
        this.topicTemp.difficulty = 30 // 设置默认值
      }

      // 验证进度必须是数字
      if (this.topicTemp.progress !== null && this.topicTemp.progress !== undefined && this.topicTemp.progress !== '') {
        const progress = Number(this.topicTemp.progress)
        if (isNaN(progress) || progress < 0 || progress > 100) {
          this.$message.error('进度必须是0-100之间的数字')
          return
        }
        this.topicTemp.progress = progress
      } else {
        this.topicTemp.progress = 0 // 设置默认值
      }

      // 验证parent_id如果存在必须是数字
      if (this.topicTemp.parent_id !== null && this.topicTemp.parent_id !== undefined && this.topicTemp.parent_id !== '') {
        const parentId = Number(this.topicTemp.parent_id)
        if (isNaN(parentId)) {
          this.$message.error('父级ID必须是数字')
          return
        }
        this.topicTemp.parent_id = parentId
      }
      if (this.topicEditId !== '') {
        this.saveTopicLoading = true
        Put(this.topicEditId, this.topicTemp).then(response => {
          this.$message.success('修改成功')
          this.topicViewData.description = this.topicTemp.description
          this.topicViewData.is_init = this.topicTemp.description.indexOf('# 一级标题(h1)') === -1
          this.topicViewData.title = this.topicTemp.title
          this.topicViewData.parent_id = this.topicTemp.parent_id
          this.topicViewData.keyword = this.topicTemp.keyword
          this.topicViewData.tag = this.topicTemp.tag
          this.topicViewData.ai_paragraph = this.topicTemp.ai_paragraph
          this.topicViewData.ai_writer = this.topicTemp.ai_writer
          this.topicViewData.star = this.topicTemp.star
          this.topicViewData.progress = this.topicTemp.progress
          this.topicViewData.project_id = this.topicTemp.project_id
          this.topicViewData.web_id = this.topicTemp.web_id
          this.topicViewData.serp_finished = this.topicTemp.serp_finished
          this.topicViewData.is_crawl_amazon = this.topicTemp.is_crawl_amazon
          this.topicViewData.serp_crawl = this.topicTemp.serp_crawl
          this.topicViewData.writer_id = this.topicTemp.writer_id
          this.topicViewData.strategy_id = this.topicTemp.strategy_id
          this.topicViewData.category_id = this.topicTemp.category_id
          // this.getList()
          // this.titleTopicDialogVisible = false
          this.updateTreeNode(this.data, this.topicEditId, this.topicTemp)
          this.saveTopicLoading = false
          // this.handleCleanTopicForm()
        }).catch(e => {
          this.$message.error('修改失败')
          // this.titleTopicDialogVisible = false
          this.resetTopiFromForContinue()
          delete this.topicTemp[extra_filed]
          this.saveTopicLoading = false
        })
      } else {
        this.saveTopicLoading = true
        AddTopic(this.topicTemp).then(response => {
          this.$message.success('保存成功')
          this.getList()
          // this.titleTopicDialogVisible = false
          this.resetTopiFromForContinue()
          delete this.topicTemp[extra_filed]
          this.saveTopicLoading = false
        }).catch(e => {
          this.notify('保存失败')
          // this.titleTopicDialogVisible = false
          this.saveTopicLoading = false
          delete this.topicTemp[extra_filed]
        })
      }
    },
    resetTopiFromForContinue() {
      this.topicEditId = ''
      this.topicTemp.title = ''
      this.topicTemp.keyword = ''
      this.topicTemp.title_template = ''
    },
    handleCleanTopicForm() {
      this.topicTemp.title = ''
      this.topicTemp.title_template = ''
      this.topicTemp.description = '# 一级标题(h1)\n## 二级标题(h2)\n### 三级标题(h3)\n#### 四级标题h4\n注意#号和内容要有空格,每行一个标题\n' +
            'AI内容+随机抓取内容:{random}\n纯随机抓取:{random-only}\n关键词替换:[keyword]'
      this.topicTemp.keyword = this.keyword
      this.topicTemp.tag = ''
      this.topicTemp.progress = 0
      this.topicTemp.parent_id = ''
      this.topicEditId = ''
    },
    handleOpenReviews(row) {
      const routeData = this.$router.resolve({ name: 'cms.bestreviewhtml', query: { k: row.keyword }})
      console.log(routeData)
      window.open(routeData.href, '_blank')
    },
    handleAddMaterial(row) {
      this.topic_id = row.id
      this.topic_title = '框架素材:[' + row.title + ']'
      this.materialVisible = true
      this.topicmaterialDrawerVisible = true
    },
    handleShowMaterial(row) {
      this.generateresponse = ''
      this.handleAddMaterial(this.topicViewData)
    },
    loadNode(node, resolve) {
      if (node.data.id === undefined) {
        return
      }
      this.expanded_ids = [node.data.id]

      // 计算当前节点的层级深度
      let currentLevel = 0
      let parentNode = node.parent
      while (parentNode && parentNode.data) {
        currentLevel++
        parentNode = parentNode.parent
      }

      // 设置分页大小，二级目录之后限制为10个
      const pagesizeForLevel = currentLevel >= 2 ? 10 : this.pagesize

      GetTopics(node.data.id, qs.stringify({
        kw: this.kwInput,
        progress_s: this.progress[0],
        progress_e: this.progress[1],
        keyword: this.keyword,
        star: this.star,
        min_star: this.stars[0],
        max_star: this.stars[1],
        page: this.page,
        pagesize: pagesizeForLevel,
        tag: this.TagInput,
        min_volume: this.volume,
        max_diff: this.difficulty,
        owner_id: this.owner_id,
        project_id: this.project_id,
        web_id: this.web_id
      }))
        .then(response => {
          const data = response.data.data.map(m => {
            this.$set(m, 'active', false)
            this.$set(m, 'deleted', false)
            return m
          })

          // 如果是二级目录之后且有更多数据，添加"查看更多"节点
          if (currentLevel >= 2 && response.data.total > pagesizeForLevel) {
            const moreNode = {
              id: `more_${node.data.id}_${Date.now()}`,
              keyword: `...还有${response.data.total - pagesizeForLevel}项（点击查看全部）`,
              title: `...还有${response.data.total - pagesizeForLevel}项（点击查看全部）`,
              children_count: 0,
              isMoreNode: true,
              parentId: node.data.id,
              totalCount: response.data.total,
              showingCount: pagesizeForLevel,
              deleted: false,
              active: false
            }
            data.push(moreNode)
          }

          this.loaddata = data
          resolve(data)
        }).catch(e => {
          this.$message.error('获取失败')
        })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    handleAddPost(row) {
      this.topic_id = row.id
      this.topic_title = '框架:[' + row.title + ']'
      this.postVisible = true
    },
    handleEditPost(row) {
      this.edit_post_id = row.post_id
      this.postEditorVisible = true
      // const link = this.$router.resolve({ name: 'editPostPut', params: { post_id: row.post_id }})
      // window.open(link.href, '_blank')
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleNodeDrop(draggingNode, dropNode, dropType, ev) {
      const movedNodeData = draggingNode.data // 被拖拽的节点数据
      const newParentNodeData = dropNode.data // 目标节点数据

      let newParentId = null

      if (dropType === 'inner') {
        // 放置在目标节点内部，新的父节点就是目标节点
        newParentId = newParentNodeData.id
      } else if (dropType === 'before' || dropType === 'after') {
        // 放置在目标节点的前或后，新的父节点是目标节点的父节点
        const parentNode = dropNode.parent
        if (parentNode && parentNode.data) {
          newParentId = parentNode.data.id
        } else {
          // 如果没有父节点，表示在根节点下
          newParentId = null
        }
      }

      // 更新节点的 parent_id
      movedNodeData.parent_id = newParentId

      // 更新后端数据，调用 API
      console.log(movedNodeData.id, newParentId)
      // this.updateNodeParentId(movedNodeData.id, newParentId);
      this.updateNodeParentId(movedNodeData.id, newParentId)
      // 如果需要，可以更新本地数据，以便界面立即反映变化
      // 如果您的后端返回更新后的数据，可以在更新后重新获取列表
    },
    updateNodeParentId(nodeId, newParentId) {
      // 调用您的 API 更新节点的 parent_id
      Put(nodeId, { parent_id: newParentId })
        .then(response => {
          this.$message.success('节点移动成功')
          // 如果需要，重新获取列表或更新本地数据
          // this.getList();
        })
        .catch(e => {
          this.$message.error('节点移动失败')
          // 如果需要，回滚本地数据的变化
        })
    },
    handleSearchNodeByParentID(row) {
      // 处理"查看更多"节点的特殊逻辑
      if (row.isMoreNode) {
        this.$confirm(`当前只显示了前${row.showingCount}项，共有${row.totalCount}项。是否查看全部？`, '查看全部子项', {
          confirmButtonText: '查看全部',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          // 临时增加页面大小来显示全部子项
          const originalPagesize = this.pagesize
          this.pagesize = row.totalCount

          // 搜索父节点以显示全部子项
          this.search_parent_id = row.parentId
          this.current_expended_node = { id: row.parentId, title: '查看全部子项' }
          this.keyword = ''
          this.id = ''
          this.operate_title = '查看全部子项'
          this.handleSearch()

          // 恢复原始页面大小
          this.$nextTick(() => {
            this.pagesize = originalPagesize
          })
        })
        return
      }

      // 普通节点的处理逻辑
      this.search_parent_id = row.id
      this.current_expended_node = row
      // this.expanded_ids = [row.id]
      this.keyword = ''
      this.id = ''
      this.operate_title = row.title
      this.handleSearch()
    },
    handleSearchNodeByKeyword(row) {
      this.current_expended_node = row
      this.expanded_ids = [row.id]
      this.keyword = row.keyword
      this.id = row.id
      this.operate_title = row.title
      this.handleSearch()
    },
    handleToTopNode() {
      this.current_expended_node = null
      this.search_parent_id = ''
      this.handleSearch()
    },
    handleClean() {
      this.kwInput = ''
      // this.current_expended_node = null
      // this.search_parent_id = ''
      this.keyword = ''
      this.id = ''
      this.operate_title = ''
      this.total = this.data.length
      this.page = 1
      this.handleSearch()
    },
    progressToolTips(val) {
      return '完成进度:' + val + '%'
    },
    starToolTips(val) {
      return '星级:' + val
    },
    copyChildrenTitles(parent_id) {
      // 在调用接口前可设置一个 loading
      this.listLoading = true

      // 调用 GetTopics 接口，根据 parent_id 查询最多 1000 条数据
      GetTopics(null, qs.stringify({
        parent_id: parent_id,
        progress_s: 0,
        progress_e: 100,
        star: this.star,
        order_by: this.order_by,
        order_desc: this.order_desc,
        owner_id: this.owner_id,
        project_id: this.project_id,
        web_id: this.web_id,
        strategy_id: this.strategy_id,
        page: 1,
        pagesize: 1000
      }))
        .then(response => {
          this.listLoading = false
          // 接口返回数据后，提取所有标题并用换行符拼起来
          const children = response.data.data || []
          const titles = children.map(item => item.title).join('\n')

          // 复制到剪贴板
          // 如果你已有封装好的 copyText/clip 工具，直接调用即可
          // 例如: copyText(titles);
          navigator.clipboard.writeText(titles)
            .then(() => {
              this.$message.success('已复制子框架标题')
            })
            .catch(() => {
              this.$message.error('复制失败')
            })
        })
        .catch(() => {
          this.listLoading = false
          this.$message.error('获取子框架标题失败')
        })
    },

    handleIDSearch(id) {
      this.keyword = ''
      this.volume = ''
      this.kwInput = ''
      this.id = ''
      this.search_parent_id = id
      // this.expanded_ids = [id]
      this.handleSearch()
    },
    handleSearch() {
      this.page = 1
      if (this.web_id) {
        this.topicTemp.web_id = this.web_id
      }
      if (this.project_id) {
        this.topicTemp.project_id = this.project_id
      }
      this.getList()
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.post__writer_finished && row.progress < 100) {
        if (row.owner_pass) {
          return 'success-row'
        } else {
          return 'warning-row'
        }
      }
      return ''
    },
    handleSelectionChange(rows) {
      this.drawer_data = rows
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleClickEdit(id) {
      const link = this.$router.resolve({ name: 'editPostPut', params: { post_id: id }})
      window.open(link.href, '_blank')
    },
    handleClickView(row) {
      // this.$router.push({ name: 'viewPost', params: { post_id: id }})
      this.topicViewData = row
      this.TopicViewDialogVisible = true
    },
    handleOpenPost(data) {
      if (data.post_url) {
        // 如果存在 post_url，在新标签页中打开
        window.open(data.post_url, '_blank')
      } else {
        // 如果不存在 post_url，在 Google 中搜索该主题
        const searchQuery = encodeURIComponent(data.title || data.keyword)
        const googleSearchUrl = `https://www.google.com/search?q=${searchQuery}`
        window.open(googleSearchUrl, '_blank')
      }
    },
    handleDirectlyEditTopic(data) {
      // this.drawer = false
      Object.keys(data).forEach(key => {
        if (data[key] !== undefined) this.topicViewData[key] = data[key]
      })
      this.copydata()
      this.topicTemp.id = data.id
      this.HanldeEditTopic()
    },
    showMutliEdit() {
      this.childTopicsEditorVisible = true
    },
    handleClickDelete(row) {
      this.deleteDialogVisible = true
      this.deleteDialogTitle = `确认要删除框架 ${row.title}?`
      this.deleteId = row.id
      this.deleteRow = row
    },
    handleDeleteConfirm() {
      // this.deleteDialogLoading = true
      this.deleteDialogVisible = false
      Delete(this.deleteId)
        .then(res => {
          this.deleteDialogLoading = false
          this.deleteDialogVisible = false
          this.$message.success('删除成功')
          console.log('op id:' + this.deleteId)
          console.log(this.data)
          for (let i = 0; i < this.data.length; i++) {
            if (this.data[i].id === this.deleteId) {
              console.log('delete row id')
              break
            }
          }
          for (let j = 0; j < this.loaddata.length; j++) {
            if (this.loaddata[j].id === this.deleteId) {
              console.log('delete children row id')
              this.loaddata[j].deleted = true
              break
            }
          }
        }).catch(e => {
          this.deleteDialogLoading = false
          this.$message.error('删除失败')
        })
    },
    handleClickShare(v, event) {
      const link = this.$router.resolve({
        name: 'viewPost',
        params: {
          post_id: v
        }
      })
      clip(window.location.origin + '/' + link.href, event)
      this.$message({
        message: '复制成功',
        type: 'success',
        duration: 1500
      })
    },
    handleChangePostFinishStatus(row) {
      Put(row.id, JSON.stringify({
        is_finished: row.is_finished,
        put_finished: 1
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: '修改状态成功',
            type: 'success',
            duration: 1000
          })
          this.getList(false)
        })
        .catch(e => {
        })
    },
    updateProjectId() {
      this.$store.dispatch('setProjectId', this.project_id)
      console.log('update project id')
    },
    isOverflowing(text) {
      const maxWidth = 300 // 根据实际情况调整
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      context.font = '14px Arial' // 根据实际使用的字体调整
      return context.measureText(text).width > maxWidth
    },

    getVolumeTagType(volume) {
      if (volume < 100) return 'info'
      if (volume < 500) return 'primary'
      if (volume < 3000) return 'warning'
      return 'success'
    },

    getDifficultyTagType(difficulty) {
      if (difficulty <= 30) return 'success'
      if (difficulty <= 50) return 'info'
      if (difficulty <= 70) return 'warning'
      return 'danger'
    },
    handleAITopicSectionAnalysisResult(result) {
      // 处理AI调研框架的结果，与handleAutoGetArticlePrompt类似的逻辑
      try {
        if (result && result.trim()) {
          // 如果返回的结果包含特定标识，说明是后台处理
          if (result.indexOf('后台生成中') !== -1) {
            this.generateresponse = result
            this.$message({
              type: 'success',
              message: '已经提交AI调研请求，可以关闭界面，钉钉会提醒结果'
            })
          } else {
            // 直接返回了内容，更新description
            this.topicTemp.description = result
            this.generateresponse = ''
            this.$message({
              type: 'success',
              message: 'AI调研框架完成，内容已更新'
            })
          }
        } else {
          this.generateresponse = 'AI调研完成，但未返回内容'
        }
      } catch (error) {
        console.error('处理AI调研结果失败:', error)
        this.generateresponse = 'AI调研结果处理失败'
        this.$message.error('AI调研结果处理失败')
      }

      this.topicpromptgenerateloading = false
    }
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 6px; /* 默认是 22px */
}
.keyword-wrapper {
      display: inline-block;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis; /* 当文本超出时显示省略号 */
    }
    /* 小屏幕设备（宽度小于600px） */
    @media (max-width: 599px) {
      .keyword-wrapper {
        max-width: 300px; /* 小屏幕上使用100%宽度 */
      }
    }

    /* 中等屏幕设备（宽度在600px至899px之间） */
    @media (min-width: 600px) and (max-width: 899px) {
      .keyword-wrapper {
        max-width: 400px; /* 中等屏幕上调整宽度为80% */
      }
    }

    /* 大屏幕设备（宽度900px及以上） */
    @media (min-width: 900px)  and (max-width: 1200px){
      .keyword-wrapper {
        max-width: 600px; /* 大屏幕上使用固定的最大宽度 */
      }
    }
     /* 大屏幕设备（宽度900px及以上） */
    @media (min-width: 1600px){
      .keyword-wrapper {
        max-width: 900px; /* 大屏幕上使用固定的最大宽度 */
      }
    }

    .keyword-text {
      font-size: 16px; /* 关键词的字体大小 */
      color: #333; /* 关键词的颜色 */
    }

    .title-text {
      font-size: 12px; /* 标题的字体大小 */
      color: #666; /* 标题的颜色，使用不那么突出的颜色 */
      display: block; /* 使标题显示在新的一行 */
      text-overflow: ellipsis; /* 文本过长时显示省略号 */
      overflow: hidden;
      white-space: nowrap;
      text-align: right;
      width: 100%; /* 设置宽度以便省略号生效 */
    }
    .el-header, .el-footer {
      background-color: #fff;
      color: #333;
      text-align: left;
      line-height: 60px;
    }

  .el-aside {
    background-color: #fff;
    border-left: 1px solid #ebeef5;
    color: #333;
    padding-top: 20px;
    padding-left: 10px;
    line-height: 250px;
  }

  .el-main {
    background-color: #fff;
    color: #333;
    text-align: center;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  /*.top {*/
  /*padding-left: 20px;*/
  /*padding-right: 20px;*/
  /*margin-bottom: 5px;*/
  /*margin-top: 28px;*/
  /*}*/

  /*.head {*/
  /*width: calc(20% - 70px);*/
  /*}*/

  /*.web {*/
  /*margin-top: 10px;*/
  /*margin-bottom: 10px;*/
  /*display: inline-block;*/
  /*width: 100%;*/
  /*}*/

  .web >>> .el-input {
    min-width: 1200px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }
  @media screen and (max-width: 1300px) {
    .app-container >>> .only_pc  {
      display: none;
    }
  }
  .app-container >>> .warning-row {
      background: oldlace;
    }

    .app-container >>> .success-row {
      background: #f0f9eb;
    }
    .app-container >>> .finished-row {
      background: #f0f9eb;
    }

  .mt-detail:hover, .svg-icon:hover {
    cursor: pointer;
  }

  .mt-detail {
    color: #1976d2;
  }

  .mt-dialog >>> .el-dialog {
    margin: 88px auto !important;
  }

  .clearfix ::after {
    content: "";
    clear: both
  }

  .mt-table {
    color: black;
    padding: 20px;
  }
  .mt-pagination {
    float: right;
    margin-top: 10px;
  }

  .mt-top {
    margin: 15px 0;
  }

  .mt-row-btn {
    float: right;
    vertical-align: middle;
    color: white;
  }

  .mt-btn {
    background-color: rgba(0, 0, 0, 0);
    background-image: none;
    border-radius: 1000px;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    border-collapse: collapse;
    border-image-outset: 0px;
    border-image-repeat: stretch;
    border-image-slice: 100%;
    border-image-source: none;
    border-image-width: 1;
    border-left-style: solid;
    border-left-width: 1px;
    border-right-style: solid;
    border-right-width: 1px;
    border-top-style: solid;
    border-top-width: 1px;
    box-sizing: border-box;
    color: #46be8a;
    cursor: pointer;
    display: block;
    float: right;
    font-family: "Helvetica Neue", Helvetica, Tahoma, Arial, "Microsoft Yahei", "Hiragino Sans GB", "WenQuanYi Micro Hei", sans-serif;
    font-size: 14px;
    font-weight: 400;
    height: 26px;
    hyphens: manual;
    line-height: 14px;
    margin-bottom: 0px;
    margin-right: 10px;
    padding: 5px;
    text-align: center;
    text-decoration-color: rgb(82, 96, 105);
    text-decoration-line: none;
    text-decoration-style: solid;
    text-rendering: optimizeLegibility;
    text-size-adjust: 100%;
    touch-action: manipulation;
    transition-delay: 0s, 0s, 0s, 0s;
    transition-duration: 0.2s, 0.2s, 0.2s, 0.2s;
    transition-property: border, color, width, background-color;
    transition-timing-function: linear, linear, linear, linear;
    user-select: none;
    vertical-align: middle;
    visibility: visible;
    white-space: nowrap;
    background: white;
  }

  .mt-btn:hover + >>> .mt-icon {
    color: #fff;
  }

  .mt-btn:hover {
    background: #46be8a;
  }

  .danger:hover {
    background-color: #F56C6C;
  }

  .danger {
    color: #F56C6C;
  }

  .default:hover {
    background-color: #62a8ea;
  }

  .default {
    color: #62a8ea;
  }

  .edit:hover {
    background-color: #909399;
  }

  .edit {
    color: #909399;
  }
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 460px;
    height: 400px;
    float: left;
    margin-right: 10px;
  }
  .mt-row-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: calc(100% - 220px);
    display: inline-block;
    vertical-align: middle;
  }

  .mt-row-btns {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
    z-index: 1!important;
  }
 .app-container >>> .el-slider__runway {
    margin: auto !important;
  }

 .app-container >>>   .custom-tree-node {
  display: flex;
    align-items: center;
   width: 100%;
    justify-content: space-between;
    font-size: 14px;
    height: 40px;
    padding-right: 8px;
    padding-top: 5px;
    padding-bottom: 5px;
  }

 .app-container >>> .tree-node-keyword {
  display: flex;
  align-items: center;
}
 .app-container >>> span.custom-tree-node {
    font-size: small;
 }
 .app-container >>> span.custom-tree-node:hover {
    border-style: solid;
    border-color: black;
    border-width: 1px;
 }
 ::v-deep .custom-tree-node:hover .keyword-text {
  color: red !important; /* Override color when hovered */
  /* 其他样式如需要 */
}
 .app-container >>> .el-tree-node__content {
   border-bottom:1px solid #ddd;
   height: 40px;
 }
  .app-container >>>  .el-tree-node__content:hover {
    height: 40px;
 }
  .custom-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px; /* 添加底部间距 */
}

.row-title {
  font-weight: bold; /* 标题加粗 */
  margin-right: 8px; /* 标题和内容之间的间距 */
}

.row-content {
  color: #555; /* 内容使用淡化的颜色 */
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  min-height: 40px; /* 确保最小高度，防止内容太少时布局错乱 */
}

.node-title {
  display: flex;
  align-items: center;
  max-width: 40%;
  min-width: 200px; /* 设置最小宽度，确保短标题时布局一致 */
  margin-right: 10px;
}

.keyword-text {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.keyword-text.deleted {
  text-decoration: line-through;
}

.children-count {
  padding: 2px 4px;
  margin-left: 5px;
  background-color: green;
  color: white;
  border-radius: 10px;
  font-size: 12px;
  flex-shrink: 0;
}

.node-info-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex: 1;
  min-width: 0; /* 允许flex item收缩到比内容更小 */
}

.node-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-right: 10px;
  min-width: 0; /* 允许flex item收缩到比内容更小 */
}

.node-info > * {
  margin-right: 5px;
  margin-bottom: 2px;
}

.node-actions {
  display: none;
  align-items: center;
  flex-wrap: wrap;
  margin-left: 10px; /* 将左边距从 5px 增加到 10px */
  margin-bottom: 2px;
}

.custom-tree-node:hover .node-actions {
  display: flex;
}

.custom-tree-node:hover .node-info {
  display: none;
}
.node-actions > * {
  margin-left: 5px;
  margin-bottom: 2px;
}

.node-actions i {
  font-size: 20px;
  cursor: pointer;
  color: #909399;
  padding: 6px; /* 增加图标的内边距，扩大点击区域 */
  border-radius: 4px; /* 可选，增加圆角效果 */
}

.node-actions i.is-active {
  color: #308004;
}

.node-actions i:hover {
  color: #409EFF;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .custom-tree-node {
    flex-direction: column;
    align-items: flex-start;
  }

  .node-title {
    max-width: 100%;
    margin-bottom: 5px;
  }

  .node-info-actions {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
  }

  .node-info {
    width: 100%;
    margin-bottom: 5px;
  }

  .node-actions {
    width: 100%;
    justify-content: flex-start;
    margin-top: 5px;
  }
}

/* 查看更多节点的特殊样式 */
.app-container >>> .el-tree-node__content .custom-tree-node .keyword-text[title*="查看"],
.app-container >>> .el-tree-node__content .custom-tree-node .keyword-text[title*="还有"] {
  color: #E6A23C !important;
  font-style: italic;
  font-weight: bold;
  cursor: pointer;
}

.app-container >>> .el-tree-node__content .custom-tree-node:hover .keyword-text[title*="查看"],
.app-container >>> .el-tree-node__content .custom-tree-node:hover .keyword-text[title*="还有"] {
  color: #D3971A !important;
  text-decoration: underline;
}

/* 更简洁的样式，通过文本内容识别 */
.keyword-text:contains("还有"),
.keyword-text:contains("查看全部") {
  color: #E6A23C !important;
  font-style: italic;
  cursor: pointer;
}
</style>
